﻿using Bangle.BLL;
using Bangle.Comman;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace Search
{
    public partial class Form1 : Form
    {
        #region  属性
        T_CompanyBLL bll = new T_CompanyBLL();
        #endregion

        int iNewCount = 0;
        List<UrlTempModel> url_temp_list = new List<UrlTempModel>();
        int iWebId = 1;

        public Form1()
        {
            InitializeComponent();
        }

        #region 事件
        private void Form1_Load(object sender, EventArgs e)
        {
            this.cb_Tile.Items.Add("一分钟");
            this.cb_Tile.Items.Add("五分钟");
            this.cb_Tile.Items.Add("十分钟");
            this.cb_Tile.Items.Add("三十分钟");

            this.cb_Tile.SelectedIndex = 2;
            this.cb_Tile.SelectedIndexChanged += cb_Tile_SelectedIndexChanged;

            this.timer1.Interval = 1000 * 60 * 10;
            this.timer1.Enabled = true;

            this.timer2.Interval = 1000 * 1;
            this.timer2.Enabled = false;

            this.btn_Start.Text = "暂停";
            this.lbl_SysStatus.Text = "状态：已运行";
            this.lbl_Msg.Text = "";

            this.notifyIcon1.Visible = true;
        }

        private void btn_Start_Click(object sender, EventArgs e)
        {
            this.timer1.Enabled = !this.timer1.Enabled;
            this.timer2.Enabled = false;

            this.lbl_Msg.Text = "";

            this.btn_Start.Text = (this.timer1.Enabled ? "暂停" : "运行");

            this.lbl_SysStatus.Text = (this.timer1.Enabled ? "状态：已运行" : "状态：已暂停");

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (iWebId == 0)
            {
                iWebId = 1;
                this.lbl_SysStatus.Text = "状态：正从【51Job】拼命获取数据中...";
                GetDataBy51JobIndex();//从51job获取数据
                this.lbl_SysStatus.Text = "状态：【51Job】获取数据完毕，等待下一次获取中...";
            }
            else
            {
                iWebId = 0;
                this.lbl_SysStatus.Text = "状态：正从【智联】拼命获取数据中...";
                GetDataByZhaopinIndex();//从智联获取数据
                this.lbl_SysStatus.Text = "状态：【智联】获取数据完毕，等待下一次获取中...";

                if (url_temp_list.Count > 0)
                {
                    timer1.Enabled = false;
                    timer2.Enabled = true;
                }
                else
                {
                    timer1.Enabled = true;
                    timer2.Enabled = false;
                }
            }
            this.lbl_Msg.Text = string.Format("【{0}】 新增：{1} 条", DateTime.Now.ToString("HH:mm:ss"), iNewCount);
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            GetDetailByZhaopin();
            this.lbl_Msg.Text = string.Format("【{0}】 新增：{1} 条", DateTime.Now.ToString("HH:mm:ss"), iNewCount);
        }

        private void cb_Tile_SelectedIndexChanged(object sender, EventArgs e)
        {
            int iTime = 1;
            switch (this.cb_Tile.SelectedIndex)
            {
                case 0:
                    iTime = 1;
                    break;
                case 1:
                    iTime = 5;
                    break;
                case 2:
                    iTime = 10;
                    break;
                case 3:
                    iTime = 30;
                    break;
            }
            this.timer1.Interval = 1000 * 60 * iTime;
        }

        private void btn_Clear_Click(object sender, EventArgs e)
        {
            iNewCount = 0;
        }
        #endregion



        #region 获取数据 http://www.51job.com/

        private void GetDataBy51JobIndex()
        {
            //this.lbl_Msg.Text = "正在拼命的获取中...";
            string _sSouceUrl = "http://www.51job.com/";
            string _sHtmlString = HttpHeler.GetHtml(_sSouceUrl);

            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
            document.LoadHtml(_sHtmlString);

            HtmlNode rootNode = document.DocumentNode;
            HtmlNodeCollection categoryNodeList = rootNode.SelectNodes("//html[1]/body[1]//a");

            foreach (HtmlNode item in categoryNodeList)
            {
                string _sHref = item.GetAttributeValue("href", "");
                string _sTitle = item.GetAttributeValue("title", "");
                if (_sTitle == "")
                {
                    _sTitle = item.InnerText;
                }

                string _sAdid = item.GetAttributeValue("adid", "");

                string _sBaseUrl = "http://companyadc.51job.com/";
                if (_sHref.Length > _sBaseUrl.Length && _sHref.Substring(0, _sBaseUrl.Length) == _sBaseUrl)
                {
                    if (bll.CheckByADUrl(_sAdid) <= 0)
                    {
                        bll.Insert("51Job首页广告", _sSouceUrl, _sAdid, _sTitle, DateTime.Now, _sHref, "", "", null, 0);
                        iNewCount++;

                        if (this.cb_IsNotice.Checked)
                        {
                            ShowWindow();
                        }
                    }
                }
            }
        }


        #endregion

        #region 获取数据 http://www.zhaopin.com/

        private void GetDataByZhaopinIndex()
        {
            string _sSouceUrl = "http://www.zhaopin.com/";
            string _sHtmlString = HttpHeler.GetHtml(_sSouceUrl, Encoding.UTF8);

            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
            document.LoadHtml(_sHtmlString);

            HtmlNode rootNode = document.DocumentNode;
            HtmlNodeCollection categoryNodeList = rootNode.SelectNodes("//html[1]/body[1]//a");

            foreach (HtmlNode item in categoryNodeList)
            {
                string _sHref = item.GetAttributeValue("href", "");

                string _sAdid = item.GetAttributeValue("onmousedown", "");
                _sAdid = "ZL" + (_sAdid.Split(',').Length > 1 ? _sAdid.Split(',')[1].Replace(")", "") : "");

                if (_sHref.IndexOf("http://special.zhaopin.com/") >= 0 || _sHref.IndexOf("http://search.51job.com/") >= 0)
                {
                    if (bll.CheckByADUrl(_sAdid) <= 0)
                    {
                        UrlTempModel model = new UrlTempModel();
                        model.ADCode = _sAdid;
                        model.Url = _sHref;
                        url_temp_list.Add(model);
                    }
                }
            }
        }

        private void GetDetailByZhaopin()
        {
            this.timer2.Enabled = false;

            if (url_temp_list.Count <= 0)
            {
                timer1.Enabled = true;
                timer2.Enabled = false;

                if (this.cb_IsNotice.Checked)
                {
                    ShowWindow();
                }

                return;
            }

            string _sUrl = url_temp_list[url_temp_list.Count - 1].Url;

            string _sHtmlString = HttpHeler.GetHtml(_sUrl, Encoding.UTF8);

            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();

            document.LoadHtml(_sHtmlString);

            string sYTitle = "";
            string sADTitle = "";
            string sADUrl = url_temp_list[url_temp_list.Count - 1].Url;
            string sADCode = url_temp_list[url_temp_list.Count - 1].ADCode;

            HtmlNode rootNode = document.DocumentNode;
            {
                HtmlNodeCollection categoryNodeList = rootNode.SelectNodes("//html[1]/head[1]/title");
                if (categoryNodeList != null && categoryNodeList.Count > 0)
                {
                    sYTitle = categoryNodeList[0].InnerText;
                    sADTitle = sYTitle.Replace("_职位搜索_智联招聘", "");

                    if (bll.CheckByADUrl(sADCode) <= 0)
                    {
                        bll.Insert("智联首页广告", sADUrl, sADCode, sADTitle, DateTime.Now, sADUrl, sYTitle, "", DateTime.Now, 0);
                        iNewCount++;
                    }
                }
            }

            //移除最后一项
            url_temp_list.RemoveAt(url_temp_list.Count - 1);

            this.timer2.Enabled = true;
        }
        #endregion


        #region 托盘
        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowWindow();
        }

        private void ShowWindow()
        {
            this.Show();
            this.ShowInTaskbar = true; //显示在系统任务栏
            this.WindowState = FormWindowState.Normal; //还原窗体
            //notifyIcon1.Visible = false; //托盘图标隐藏
        }

        private void 隐藏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
            this.ShowInTaskbar = false; //不显示在系统任务栏
            //notifyIcon1.Visible = true; //托盘图标可见
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //注意判断关闭事件Reason来源于窗体按钮，否则用菜单退出时无法退出!
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;    //取消"关闭窗口"事件
                this.WindowState = FormWindowState.Minimized;    //使关闭时窗口向右下角缩小的效果
                this.Hide();
                return;
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.Show();
            WindowState = FormWindowState.Normal;
            this.Focus();

        }

        #endregion

    }

    public class UrlTempModel
    {
        public string ADCode { get; set; }
        public string Url { get; set; }
    }
}
